#include "FontManager.h"
#include "../tools/Log.h"

#include <FTGL/ftgl.h>

typedef FontList::const_iterator FontIter;

FontManager& FontManager::Instance() {
	static FontManager tm;
	return tm;
}

FontManager::~FontManager() {
	FontIter font;
	for(font = fonts.begin(); font != fonts.end(); font++) {
		delete (*font).second;
	}

	fonts.clear();
}

FTFont* FontManager::getFont(const char *filename, int size)
{
	char buf[256];
	sprintf(buf, "%s%i", filename, size);
	string fontKey = string(buf);

	FontIter result = fonts.find(fontKey);
	if(result != fonts.end()) {
		return result->second;
	}
	
#if defined(__APPLE_CC__)
	string fullpath = "/Volumes/Macintosh HD/Library/Fonts/";
#else
	string fullpath = "/usr/share/fonts/truetype/freefont/";
#endif
	fullpath += string(filename);

	FTFont* font = new FTPolygonFont(fullpath.c_str());

	if(font->Error()) {
		lout << "WARNING: FontManager - Font " << fullpath << " failed to open"<< endl;
		delete font;
		return NULL;
	}

	if(!font->FaceSize(size)) {
		lout << "Font " << filename << " failed to set size " << size << endl;
		delete font;
		return NULL;
	}

	fonts[fontKey] = font;
	
	return font;
}
